package com.dotflat.physicalevaluate.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dotflat.physicalevaluate.constant.MeasureConstant;
import com.dotflat.physicalevaluate.domain.importexport.PhysicEvaluateImportRecord;
import com.dotflat.physicalevaluate.domain.pe.Dimension;
import com.dotflat.physicalevaluate.domain.pe.Measure;
import com.dotflat.physicalevaluate.domain.pe.PERecord;
import com.dotflat.physicalevaluate.domain.pe.RelRecordMeasure;
import com.dotflat.physicalevaluate.repository.*;
import com.dotflat.physicalevaluate.service.EvaluateConclusionService;
import com.dotflat.physicalevaluate.service.PhysicEvaluateService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.rel.RelClassesChildren;
import com.matt.foundation.model.ErrorCode;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.rel.RelClassesChildrenRepository;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.UploadService;
import com.tuo51.foudation.constant.CommonConstant;
import com.tuo51.foudation.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.dotflat.physicalevaluate.constant.MeasureConstant.HEIGHT;
import static com.dotflat.physicalevaluate.constant.MeasureConstant.WEIGHT;
import static org.apache.poi.ss.usermodel.CellType.STRING;

@Service
@Slf4j
public class PhysicEvaluateServiceImpl implements PhysicEvaluateService {


    @Autowired
    private ClassesService classesService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    private RecordRepository recordRepository;

    @Autowired
    private RelRecordMeasureRepository relRecordMeasureRepository;

    @Autowired
    private ImportRecordRepository importRecordRepository;

    @Autowired
    private MeasureRepository measureRepository;

    @Autowired
    UploadService uploadService;

    @Autowired
    EvaluateConclusionService conclusionService;

    @Autowired
    DimensionRepository dimensionRepository;

    private double doubleFromCell(XSSFCell cell){
        if(cell.getCellType() == STRING){
            return Double.parseDouble(cell.getStringCellValue());
        }else{
            return cell.getNumericCellValue();
        }
    }

    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public PhysicEvaluateImportRecord importEvaluateRAW(String areaId, StaffDTO staff, Classes classes, MultipartFile file) {
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

//        Organization org = staffService.staffOrgnization(staff);

        //
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //仅使用第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            //创建导入记录
            PhysicEvaluateImportRecord importRecord = new PhysicEvaluateImportRecord();

            importRecord.setAreaId(staff.getAreaId());
            importRecord.setClassId(classes.getId());
            importRecord.setClassName(classes.getName());
            importRecord.setCreateTeacherId(staff.getId());
            importRecord.setFinished(true);

            importRecord.setCreateTeacherName(staff.getRealName());

            importRecordRepository.save(importRecord);

            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();

            if (rows <= 0){
                return null;
            }

            int fullCount = 0;
            int failedCount = 0;

            //
            HashSet <RelRecordMeasure> relCache = new HashSet<>();

            //遍历每一行，注意：第 0 行为标题
            for (int j = 1; j < rows; j++) {
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);

                if (row == null){
                    continue;
                }

                //姓名	性别	生日	身高(cm)	体重(kg)	坐位体前屈(cm)	立定跳远(cm)	网球掷远(m)	双脚连续跳(s)	10米折返跑(s)	走平衡木(s)
                String name = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String genderStr = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                Date birthday = null;
                XSSFCell birthdayCell = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                if (birthdayCell.getCellType() == STRING){
                    String birthdayStr = birthdayCell.getStringCellValue();
                    birthday = DateUtil.parseToDate(birthdayStr);
                }else {
                    birthday = birthdayCell.getDateCellValue();
                }

                double height = doubleFromCell(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));

                if (StringUtils.isAnyEmpty(name, genderStr) || birthday == null){
                    continue;
                }

                int gender = CommonConstant.Gender.get(genderStr).codeOf();

                //找到宝宝
                Children children = classesService.getAnyMemberByClassesIdAndName(areaId, classes.getId(), name);

                if (children == null){
                    throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
                }

                double month = DateUtil.betweenMonthsV2(new Date(), children.getBirthday());
                if (month < 36){
                    month += 3;
                }
                if (month < 36){
                    throw new BusinessException(ErrorCode.CHILDREN_BIRTHDAY_NOT_EXIST, name + "小朋友年龄过小。");
                }


                //
                PERecord record = recordForChildren(staff, children, birthday, importRecord, height);
                record.setFinished(true);
                recordRepository.save(record);


                HashSet <RelRecordMeasure> recordCache = new HashSet<>();
                int fullScore = 0;
                for (int r = 4; r <= 10; r++ ){
                    MeasureConstant cnst = MeasureConstant.getByIndex(r);

                    double val = doubleFromCell(row.getCell(r, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));

                    String valStr = String.format("%d", (int)(val * 10));

                    String staticId = cnst.getStaticId() + "";

                    double reserve = 0;
                    if (r == 4) {  //体重
                        reserve = height * 10;
                    }else{
                        if(month - cnst.getMaxMonth() > 12){
                            throw new BusinessException(com.matt.commons.model.ErrorCode.DATE_FORMAT_ERROR, "月龄超出量表范围："+ name + "：" + month + "月龄");
                        }else if(month > cnst.getMaxMonth()){
                            reserve = cnst.getMaxMonth() * 10 - 0.1;
                        }else{
                            reserve = month * 10;
                        }
                    }

                    Measure m = measureRepository.findMeasureBy(staticId, gender, reserve, Double.parseDouble(valStr));


                    //创建 record measure 关系
                    RelRecordMeasure rel = relForMeasure(record, m, cnst, val);
                    fullScore += rel.getRankVal();

                    rel.setSeq(cnst.getStaticId());

                    recordCache.add(rel);


                    //标记身高体重
                    if (cnst == WEIGHT){
                        record.setWeight(valStr);
                    }
                }

                if (fullScore == 0){
                    throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, name + " 宝宝没有测评结果");
                }else {
                    relCache.addAll(recordCache);
                }

                record.setDq(fullScore * 10);
                record.setRating(conclusionService.rankDesc(fullScore));
                recordRepository.save(record);

                fullCount += 1;
            }


//            保存关系
            relRecordMeasureRepository.saveAll(relCache);

//            保存记录
            importRecord.setFullCount(fullCount);
            importRecord.setFinished(true);

//            保存文件去oss
            String ossFile = uploadService.uploadCommonFile(staff.getId(), "import_xlxs", file);

            //保存
            if(StringUtils.isNotEmpty(ossFile)) {
                importRecord.setImportFile(ossFile);
            }

            importRecordRepository.saveAndFlush(importRecord);

            importRecord = importRecordRepository.getOne(importRecord.getId());

            return importRecord;

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
    }

    private void rankMeasure(RelRecordMeasure rel, Measure m){
        if (m != null){
            rel.setMeasureId(m.getId());
            rel.setUnit(m.getUnit());
            rel.setRankVal(m.getRank());
            rel.setRankStr(m.getValue());;
        }else{
            rel.setUnit("--");
            rel.setRankVal(0);
            rel.setRankStr("未达成");;
        }
    }

    private RelRecordMeasure relForMeasure(PERecord record, Measure m, MeasureConstant cnst, double val){
        RelRecordMeasure rel = new RelRecordMeasure();

        rel.setRecord(record);
        rel.setMeasureValue(val + "");
        rel.setDimension(cnst.getDimension());
        rel.setProject(cnst.getSport());
        rel.setSeq(cnst.getStaticId());

        rankMeasure(rel, m);

        return rel;
    }

    private PERecord recordForChildren(StaffDTO staff, Children c, Date birthday, PhysicEvaluateImportRecord importRecord, double height){

        PERecord record = new PERecord();

        record.setAreaId(staff.getAreaId());
        record.setChildrenId(c.getId());
        record.setChildrenName(c.getName());
        record.setGender(c.getGender());
        record.setBirthday(birthday);
        record.setEvaluatingDate(new Date());
        record.setImportRecord(importRecord);
        record.setCreateTeacherId(staff.getId());
        record.setCreateTeacherName(staff.getRealName());
        record.setHeight(String.format("%d", (int)(height * 10)));
        record.setMonth((int)(DateUtil.betweenMonthsV2(new Date(), birthday) + 0.5));

        return record;
    }

    public boolean deleteReport(StaffDTO staff, String importRecordId){

        PhysicEvaluateImportRecord record = importRecordRepository.getByCreateTeacherIdAndId(staff.getId(), importRecordId);

        if (record == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST,"记录不存在");
        }

        importRecordRepository.delete(record);

        return true;
    }

    public PhysicEvaluateImportRecord getByStaffIdAndId(String staffId, String id){

        PhysicEvaluateImportRecord record = importRecordRepository.getByCreateTeacherIdAndId(staffId, id);

        if (record == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST,"记录不存在");
        }

        return record;
    }


    @Override
    public Page<PERecord> getEvaluatePage(StaffDTO staff, String classesId, String childrenName, PagerQuery query){

        List<String> childrenIds = null;
        if(StringUtils.isNotBlank(classesId)) {
            Classes c = classesService.getClassesById(staff.getAreaId(), classesId);
            if (c == null){
                throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "班级不存在");
            }

            List<RelClassesChildren> rels = relClassesChildrenRepository.findAllByClassesId(classesId);
            childrenIds = rels.stream().map(o->o.getChildrenId()).collect(Collectors.toList());
        }

        Pageable pageable = PageRequest.of(query.getPageNum(), query.getPageSize());

        List<String> finalChildrenIds = childrenIds;
        Specification<PERecord> specification = new Specification<PERecord>() {
            @Override
            public Predicate toPredicate(Root<PERecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                CriteriaBuilder.In<Object> p4 = null;
                if(finalChildrenIds != null && finalChildrenIds.size() > 0){
                    p4 = criteriaBuilder.in(root.get("childrenId"));
                    for (String id : finalChildrenIds){
                        p4.value(id);
                    }
                }

                Predicate p3 = criteriaBuilder.equal(root.get("deleted"), 0);
                Predicate p2 = criteriaBuilder.equal(root.get("finished"), 1);

                Predicate p1 = null;
                if (StringUtils.isNotBlank(childrenName)){
                    p1 = criteriaBuilder.like(root.get("childrenName"), "%" + childrenName + "%");
                }

                Predicate p0 = criteriaBuilder.and(p2, p3);
                if (p4 != null){
                    p0 = criteriaBuilder.and(p0, p4);
                }
                if (p1 != null){
                    p0 = criteriaBuilder.and(p0, p1);
                }

                query.where(p0);

                return query.getRestriction();
            }
        };
        Page<PERecord> page = recordRepository.findAll(specification, pageable);

        return page;
    }

    @Override
    public PhysicEvaluateImportRecord newRecord(StaffDTO staff, String classId){

        Classes classes = classesService.getClassesById(staff.getAreaId(), classId);

        PhysicEvaluateImportRecord importRecord = new PhysicEvaluateImportRecord();

        importRecord.setAreaId(staff.getAreaId());
        importRecord.setClassId(classes.getId());
        importRecord.setClassName(classes.getName());
        importRecord.setCreateTeacherId(staff.getId());
        importRecord.setCreateTeacherName(staff.getRealName());
        importRecord.setFullCount(0);
        importRecord.setFinished(false);

        importRecordRepository.save(importRecord);

        return importRecord;
    }

    @Override
    public Map addRecordValue(StaffDTO staff, String recordId, String childrenId, Integer type, String value){

        //找到对应的record
        PhysicEvaluateImportRecord importRecord = importRecordRepository.getByCreateTeacherIdAndId(staff.getId(), recordId);
        if (importRecord == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "导入记录不存在");
        }

        //找到对应的宝宝
        Children children = childrenService.getByIdAndAreaId(childrenId, staff.getAreaId());
        if (children == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        //找到宝宝是不是有对应的record
        PERecord record = recordRepository.getOneByChildrenIdAndImportRecordAndFinishedIsFalseAndDeletedIsFalse(childrenId, importRecord );
        if (record == null){
            record = recordForChildren(staff, children, children.getBirthday(), importRecord, 0);
        }

        //找到对应的维度
        //TODO: finish this method

        return null;
    }

    @Override
    public Integer addRecordValues(StaffDTO staff, String recordId, Integer type, String values){

        //找到对应的record
        PhysicEvaluateImportRecord importRecord = importRecordRepository.getByCreateTeacherIdAndId(staff.getId(), recordId);
        if (importRecord == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "导入记录不存在");
        }

        //cnst
        MeasureConstant cnst = MeasureConstant.get(type);

        int typeHistory = importRecord.getTypeHistory();
        typeHistory |= cnst.getHistoryMask();
        if (typeHistory != importRecord.getTypeHistory()) {
            importRecord.setTypeHistory(typeHistory);
            importRecordRepository.save(importRecord);
        }

        if (cnst == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "type类型错误");
        }

        //values object
        JSONObject valuesMap = JSON.parseObject(values);

        Set<Map.Entry<String, Object>> entries = valuesMap.entrySet();
        Integer count = 0;
        for (Map.Entry<String, Object> entry : entries){
            String childrenId = entry.getKey();
            String valStr = entry.getValue().toString();

            //找到对应的宝宝
            Children children = childrenService.getByIdAndAreaId(childrenId, staff.getAreaId());
            if (children == null){
                throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
            }

            //更新宝宝对象
            if (cnst == WEIGHT){
                children.setWeight(valStr);
            }else if (cnst == HEIGHT){
                children.setHeight(valStr);
            }
            if (cnst == WEIGHT || cnst == HEIGHT){
                childrenRepository.save(children);
            }

            //计算变量
            double month = DateUtil.betweenMonthsV2(new Date(), children.getBirthday());
            if (month < 36){
                month += 3;
            }
            if (month < 36){
                throw new BusinessException(ErrorCode.CHILDREN_BIRTHDAY_NOT_EXIST, children.getName() + "小朋友年龄过小。");
            }

            double reserve = 0;
            if (cnst == WEIGHT) {  //体重
                if (children.getHeight() == null){
                    throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, children.getName() + "没有身高信息，无法测评体重");
                }
                reserve = Double.parseDouble(children.getHeight()) * 10;
            }else{
                if(month - cnst.getMaxMonth() > 12){
                    throw new BusinessException(com.matt.commons.model.ErrorCode.DATE_FORMAT_ERROR, "月龄超出量表范围："+ children.getName() + "：" + month + "月龄");
                }else if(month > cnst.getMaxMonth()){
                    reserve = cnst.getMaxMonth() * 10 - 0.1;
                }else{
                    reserve = month * 10;
                }
            }

            //找到对应的measure
            Measure m = measureRepository.findMeasureBy(cnst.getStaticId()+"", children.getGender(), reserve, Double.parseDouble(valStr));

            //找到记录
            PERecord record = recordRepository.getOneByChildrenIdAndImportRecordAndFinishedIsFalseAndDeletedIsFalse(childrenId, importRecord );
            if (record == null){
                record = recordForChildren(staff, children, children.getBirthday(), importRecord, 0);
            }

            //处理身高体重
            if (cnst == WEIGHT){
                record.setWeight(valStr);
            }else if (cnst == HEIGHT){
                record.setHeight(valStr);
            }
            recordRepository.save(record);



            //找到对应的关系
            RelRecordMeasure rel = relRecordMeasureRepository.getByRecordAndDimension(record, cnst.getDimension());
            if (rel == null){
                rel = relForMeasure(record, m, cnst, Double.parseDouble(valStr));
            } else {
                rankMeasure(rel, m);
            }
            relRecordMeasureRepository.save(rel);

            count ++;
        }

        return count;
    }

    @Override
    public PhysicEvaluateImportRecord finishDraft(StaffDTO staff, String recordId) {

        //找到对应的record
        PhysicEvaluateImportRecord importRecord = importRecordRepository.getByCreateTeacherIdAndId(staff.getId(), recordId);
        if (importRecord == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "导入记录不存在");
        }

        //结束导入记录
        if (importRecord.getFinished()){
            throw new BusinessException(ErrorCode.OPERATION_DUPLICATED, "已经完成");
        }
        importRecord.setFinished(true);

        //找到所有的PERecord
        List<PERecord> reports = importRecord.getRecords();

        int fullScore = 0;
        for (PERecord record : reports){

            List<RelRecordMeasure> rels = record.getRels();
            for (RelRecordMeasure rel : rels){
                fullScore += rel.getRankVal();
            }

            if (fullScore == 0){
                //throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, record.getChildrenName() + " 宝宝没有测评结果");
                continue; //这个报告不要了
            }

            record.setDq(fullScore * 10);
            record.setRating(conclusionService.rankDesc(fullScore));

            record.setFinished(true);
        }

        recordRepository.saveAll(reports);

        return importRecord;
    }


    @Override
    public PhysicEvaluateImportRecord draftRecord(StaffDTO staff, String classId){
        PhysicEvaluateImportRecord importRecord = importRecordRepository.findTop1ByCreateTeacherIdAndClassIdOrderByCreatedDesc(staff.getId(), classId);

        if (importRecord.getFinished()){
            return null;
        }

        return importRecord;
    }

    @Override
    public PERecord addReport(StaffDTO staff, Children c, String values){
        double month = DateUtil.betweenMonthsV2(new Date(), c.getBirthday());
        if (month < 36){
            month += 3;
        }
        if (month < 36){
            throw new BusinessException(ErrorCode.CHILDREN_BIRTHDAY_NOT_EXIST, c.getName() + "小朋友年龄过小。");
        }

        JSONArray comps = JSON.parseArray(values);
        if (comps.size() != 8){
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误");
        }

        double height = Double.parseDouble(comps.get(0).toString());

        //
        c.setHeight(String.format("%.2f", height));
        childrenRepository.save(c);

        //
        PERecord record = recordForChildren(staff, c, c.getBirthday(), null, height);
        recordRepository.save(record);

        HashSet <RelRecordMeasure> relCache = new HashSet<>();

        int fullScore = 0;
        for (int r = 1; r < comps.size(); r++ ){
            MeasureConstant cnst = MeasureConstant.get(r+1);

            double val = Double.parseDouble(comps.get(r).toString());

            String valStr = String.format("%d", (int)(val * 10));

            String staticId = cnst.getStaticId() + "";

            double reserve = 0;
            if (r == 1) {  //体重
                reserve = height * 10;
            }else{
                if(month - cnst.getMaxMonth() > 12){
                    throw new BusinessException(com.matt.commons.model.ErrorCode.DATE_FORMAT_ERROR, "月龄超出量表范围："+ c.getName() + "：" + month + "月龄");
                }else if(month > cnst.getMaxMonth()){
                    reserve = cnst.getMaxMonth() * 10 - 0.1;
                }else{
                    reserve = month * 10;
                }
            }

            Measure m = measureRepository.findMeasureBy(staticId, c.getGender(), reserve, Double.parseDouble(valStr));

            if (m == null){
                throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, cnst.getStaticId() + ":" + cnst.getDimension() + "没有测评结果");
            }

            //创建 record measure 关系
            RelRecordMeasure rel = relForMeasure(record, m, cnst, val);
            fullScore += rel.getRankVal();

            rel.setSeq(cnst.getStaticId());

            //标记身高体重，更新宝宝对象
            boolean childrenModified = false;
            if (cnst == WEIGHT){
                record.setWeight(valStr);
                c.setWeight(valStr);
                childrenModified = true;
            }
            if (childrenModified){
                childrenRepository.save(c);
            }

            //加入cache
            relCache.add(rel);
        }

        if (fullScore == 0){
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, c.getName() + " 宝宝没有测评结果");
        }

        //保存单项得分
        relRecordMeasureRepository.saveAll(relCache);

        //总分
        record.setDq(fullScore * 10);
        record.setRating(conclusionService.rankDesc(fullScore));
        record.setFinished(true);
        recordRepository.save(record);

        return record;
    }

    @Override
    public PERecord getEvaluateDetail(String evaluateId) {
        return getEvaluateDetailById(null, evaluateId, null);
    }

    public PERecord getEvaluateDetail(String areaId, String evaluateId) {
        return getEvaluateDetailById(areaId, evaluateId, null);
    }

    @Override
    public PERecord getEvaluateDetailById(String areaId, String evaluateId, String recommendChannel){
        PERecord record = null;

        if(areaId == null){
            record = recordRepository.getOne(evaluateId);
            if (record.getDeleted()){
                record = null;
            }
        }else {
            record = recordRepository.findFirstByAreaIdAndIdAndDeletedIsFalse(areaId, evaluateId);
        }

        if(record == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "没有测评记录");
        }

        //TODO: 填写 dimension 对象
        for (RelRecordMeasure rel : record.getRels()){
            if (rel.getMeasureId() == null){
                continue;
            }
            Measure m = measureRepository.getOne(rel.getMeasureId());
            rel.setMeasure(m);

            Dimension dim = dimensionRepository.getTop1ByName(rel.getDimension());
            rel.setDim(dim);
        }

        return record;
    }
}
